package captchalogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/mojocn/base64Captcha"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type CaptchaForGetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCaptchaForGetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CaptchaForGetLogic {
	return &CaptchaForGetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CaptchaForGetLogic) CaptchaForGet(in *syspb.CaptchaForGetReq) (*syspb.CaptchaForGetResp, error) {
	driver := l.svcCtx.Captcha.Driver.ConvertFonts()
	c := base64Captcha.NewCaptcha(driver, l.svcCtx.Captcha.Store)

	// 生成验证码
	idKeyC, base64stringC, err := c.Generate()
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("获取验证码失败"),
			tool.GetErrMsgFormat("get captcha"), err, in)
	}

	return &syspb.CaptchaForGetResp{
		IdKeyC:        idKeyC,
		Base64StringC: base64stringC,
	}, nil
}
